//
//  ViewController.m
//  duilian
//
//  Created by shaojinkuang on 6/13/16.
//  Copyright © 2016 shaojinkuang. All rights reserved.
//

#import "ViewController.h"

#import "DLProducer.h"
#import "UIView+SDAutoLayout.h"

//数据源
#import "DLAbstractItem.h"
//cell
#import "DLCell.h"

#import "DLViewController.h"
#import "CustomAnimatior.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UIViewControllerTransitioningDelegate>
@property (nonatomic, strong) UITextField* inputTF;
@property (nonatomic, strong) NSMutableArray* itemArray;
@property (nonatomic, strong) UITableView* tableView;
//记录当前的level并且与点击的item中的level做比较
@property (nonatomic, assign) int currentLevel;
@property (nonatomic, strong) DLProducer* producer;

@property (nonatomic, strong) UILabel* upLabel;
@property (nonatomic, strong) UILabel* downLabel;

@property (nonatomic, strong) UIButton* generateDL;
@property (nonatomic, strong) CustomAnimatior* presentAnimation;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor colorWithRed:23/255.0f green:44/255.0f blue:60/255.0f alpha:1.0f];
    self.itemArray = [NSMutableArray array];
    self.currentLevel = 0;
    self.producer = [[DLProducer alloc] init];
    _presentAnimation = [CustomAnimatior new];
    
    [self setupViews];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - network process
- (void)getNetWorkData:(NSString*)message {
    
    //删除上次产生的数据
    [self.itemArray removeAllObjects];
    NSUInteger length = message.length;
    NSMutableString* pattern = [NSMutableString string];
    for (int i = 0; i < length; i++) {
        [pattern appendString:@"0"];
    }
    
    NSDictionary* params = @{@"shanglian":message,
                             @"xialianLocker":pattern,
                             @"isUpdate":@NO};
    
     __weak typeof(self) weakSelf = self;
    [self.producer getAllXiaLianContent:params cb:^(id object) {
        if (weakSelf != nil) {
            ViewController* strongSelf = weakSelf;
            for (id value in object) {
                DLItem* item = (DLItem*)value;
                NSArray* xiaArray = [item getXialianCandidates];
                DLAbstractItem* dlItem = [DLAbstractItem new];
                dlItem.title = [item getSegmentPattern];
                dlItem.childrenItem = xiaArray;
                dlItem.level = self.currentLevel;
                [strongSelf.itemArray addObject:dlItem];
            }
            [strongSelf.tableView reloadData];
        }
        
    }];
}
#pragma mark - tapFunction
- (void)downTapFunction:(id)sender {
    
    //[self.tableView sd_clearAutoLayoutSettings];
//    CGRect rect = self.tableView.frame;
//    rect.size.height = self.inputTF.frame.size.height;
//    self.tableView.frame = rect;
    
    [self getNetWorkData:self.inputTF.text];
}
- (void)generateDuiLian:(id)sender {
    DLViewController* dlVC = [[DLViewController alloc] init];
    dlVC.transitioningDelegate = self;
    [self presentViewController:dlVC animated:YES completion:nil];
}
#pragma mark - UIViewControllerTransitioningDelegate methods
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    
    _presentAnimation.duration = 1;
    self.presentAnimation.reverse = NO;
    return self.presentAnimation;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    
    self.presentAnimation.reverse = YES;
    
    return self.presentAnimation;
}

- (void)oneFunction {
    int a = 3;
    NSString* b = [NSString stringWithFormat:@"it is %d",a];
    [self testFunction:a name:b];
}
- (void)testFunction:(int)a name:(NSString*)b {
    NSLog(@"a is %d b is %@",a,b);
}
#pragma mark - addView
- (void)setupViews {
    
   
    //添加上联指示
    {
        self.upLabel = [UILabel new];
        self.upLabel.text = @"拟上联";
        self.upLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:self.upLabel];
        //添加下联指示
        self.downLabel = [UILabel new];
        self.downLabel.text = @"出下联";
        self.downLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:self.downLabel];
    }
    
    self.downLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer* downTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(downTapFunction:)];
    [self.downLabel addGestureRecognizer:downTap];
    
    {
        self.inputTF = [UITextField new];
        self.inputTF.textAlignment = NSTextAlignmentCenter;
        self.inputTF.backgroundColor = [UIColor whiteColor];
        //self.inputTF.font = [UIFont fontWithName:@"JSouJingSu" size:20.0f];
        self.inputTF.layer.cornerRadius = 5.0f;
        self.inputTF.delegate = self;
        self.inputTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        
        
        [self.view addSubview:self.inputTF];
    }
    
    
    
    {
        //约束每一个控件的位置
        self.upLabel.sd_layout.leftSpaceToView(self.view,10)
        .topSpaceToView(self.view,20).heightIs(40).widthRatioToView(self.view,0.2);
        
        self.inputTF.sd_layout.leftSpaceToView(self.upLabel,10)
        .topSpaceToView(self.view,20)
        .heightIs(40)
        .rightSpaceToView(self.view,10);
        
        self.downLabel.sd_layout.leftSpaceToView(self.view,10)
        .topSpaceToView(self.upLabel,10).heightIs(40).widthRatioToView(self.view,0.2);
        
        [self.inputTF updateLayout];
        [self.downLabel updateLayout];
    }
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.inputTF.frame), CGRectGetMinY(self.downLabel.frame), CGRectGetWidth(self.inputTF.frame), CGRectGetHeight(self.inputTF.frame) * 10) style:UITableViewStylePlain];
    self.tableView .delegate = self;
    self.tableView .dataSource = self;
    self.tableView.layer.cornerRadius = 5.0f;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    self.generateDL = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.generateDL setTitle:@"生成对联" forState:UIControlStateNormal];
    [self.view addSubview:self.generateDL];
    
    CGSize size = self.view.bounds.size;
    self.generateDL.sd_layout.leftSpaceToView(self.view,size.width/2 - 50)
    .topSpaceToView(self.view,size.height/2).heightIs(40).rightSpaceToView(self.view,size.width/2 - 50);
    
    
    [self.generateDL addTarget:self action:@selector(generateDuiLian:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

#pragma mark - dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.itemArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* identity = @"cell";
    DLCell* cell = (DLCell*)[tableView dequeueReusableCellWithIdentifier:identity];
    if (cell == nil) {
        cell = [[DLCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identity];
        //cell.textLabel.textAlignment = NSTextAlignmentCenter;
        //cell.textLabel.font =
        
    }
    cell.selectBtn.hidden = YES;
    //NSLog(@"current level is %d",self.currentLevel);
    DLAbstractItem* item = self.itemArray[indexPath.row];
    
    cell.title.text = item.title;
    //一般block的参数为传过来的对应的一些值
    cell.myBlock = ^() {
        NSLog(@"yes");
    };
    return cell;
}
#pragma mark - Delegate 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    DLAbstractItem* item = self.itemArray[indexPath.row];
    [self processData:item row:row];

}
#pragma mark - process
- (void)processData:(DLAbstractItem*)item row:(NSInteger)row{
    //int level = item.level;
    
    NSUInteger number = self.itemArray.count;
    //NSLog(@"item level is %d current level is %d",item.level,self.currentLevel);
    if (item.level == self.currentLevel) {
        
        self.currentLevel++;
        if (item.level == 1 && self.currentLevel == 2) {
            
            //NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            //DLCell* cell = (DLCell*)[self.tableView cellForRowAtIndexPath:indexPath];
            //cell.selectBtn.hidden = NO;
            self.downLabel.text = @"选下联";
            
        }
        DLAbstractItem* temp = [DLAbstractItem new];
        temp.level = self.currentLevel - 1;
        temp.childrenItem = [NSArray arrayWithArray:self.itemArray];
        temp.title = @"全部数据";
        [self.tableView beginUpdates];
        //先删除之前的数据选项
        
        //NSMutableArray* deleteArray = [NSMutableArray array];
        NSRange afterRange = NSMakeRange(row + 1, number - row - 1);
        NSArray* deleteArray = [NSArray arrayWithArray:[self.itemArray subarrayWithRange:afterRange]];
        [self.itemArray removeObjectsInArray:deleteArray];
        
        NSRange frontRange = NSMakeRange(0, row);
        deleteArray = [NSArray arrayWithArray:[self.itemArray subarrayWithRange:frontRange]];
        
        [self.itemArray removeObjectsInArray:deleteArray];
        //再删除tableview上的列表cell
        NSMutableArray* deleteIndexArray = [NSMutableArray array];
        for (int i = 0; i < row;i++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [deleteIndexArray addObject:indexPath];
        }
        [self.tableView deleteRowsAtIndexPaths:deleteIndexArray withRowAnimation:UITableViewRowAnimationFade];
        
        for (int i = row + 1; i < number; i++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [deleteIndexArray addObject:indexPath];
        }
        [self.tableView deleteRowsAtIndexPaths:deleteIndexArray withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        
        //    //更改目前的数据源
        [self.itemArray removeAllObjects];
        //
        
        
        [self.itemArray addObject:temp];
        NSMutableArray* insertIndexArray = [NSMutableArray array];
        int i = 0;
        for (id object in item.childrenItem) {
            DLAbstractItem* value = [DLAbstractItem new];
            value.level = self.currentLevel;
            value.childrenItem = nil;
            value.title = object;
            [self.itemArray addObject:value];
            
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i  inSection:0];
            i++;
            [insertIndexArray addObject:indexPath];
        }
        [self.tableView insertRowsAtIndexPaths:insertIndexArray withRowAnimation:UITableViewRowAnimationFade];
    }else {
        NSLog(@"返回上一层");
        
        self.currentLevel--;
        [self.tableView beginUpdates];
        
        NSMutableArray* insertIndexArray = [NSMutableArray array];
        int count = self.itemArray.count;
        for (int i = 0; i < count; i++) {
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [insertIndexArray addObject:indexPath];
        }
        [self.itemArray removeAllObjects];
        [self.tableView deleteRowsAtIndexPaths:insertIndexArray withRowAnimation:UITableViewRowAnimationFade];
        
        [insertIndexArray removeAllObjects];
        count = item.childrenItem.count;
        for (int i = 0; i < count; i++) {
            DLAbstractItem* value = item.childrenItem[i];
            [self.itemArray addObject:value];
            
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [insertIndexArray addObject:indexPath];
        }
        [self.tableView insertRowsAtIndexPaths:insertIndexArray withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        
        
    }
    
}

#pragma mark UITextfield Delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self getNetWorkData:textField.text];
    return YES;
}
#pragma mark UITouch Delegate methods
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
